import {onMounted, onUnmounted} from 'vue'
import {WINDOW_MOVE_EVENT} from '@/utils/event'
import {getStorage, setStorage} from '@/utils/localStorage'

type Point2d = {
  x: number;
  y: number;
}

export default function watchDrag() {
  // 存储位置的localstorage key
  const POSITION_STORAGE = 'window_position'
  // 绝对定位位置
  let absPoint: Point2d = getStorage(POSITION_STORAGE)
  // 鼠标按下时的位置
  let basePoint: Point2d
  // 是否正在移动
  let isMove = false

  onMounted(() => {
    // 设置上一次移动的位置，此处使用setTimeout降低优先级，避免设置失败
    setTimeout(
      () => window.ipcRenderer.send(WINDOW_MOVE_EVENT, absPoint),
      0
    )
    window.addEventListener('mousedown', handlerMouseDown)
    window.addEventListener('mousemove', handlerMouseMove)
    window.addEventListener('mouseup', handlerMouseUp)
  })

  onUnmounted(() => {
    window.removeEventListener('mousedown', handlerMouseDown)
    window.removeEventListener('mousemove', handlerMouseMove)
    window.removeEventListener('mouseup', handlerMouseUp)
  })

// 鼠标按下回调
  function handlerMouseDown(e: MouseEvent) {
    isMove = true
    basePoint = {x: e.x, y: e.y}
  }

// 鼠标移动回调
  function handlerMouseMove(e: MouseEvent) {
    if (!isMove) return

    absPoint = {
      x: e.screenX - basePoint.x,
      y: e.screenY - basePoint.y
    }

    window.ipcRenderer.send(WINDOW_MOVE_EVENT, absPoint)
  }

// 鼠标松开回调
  function handlerMouseUp() {
    isMove = false
    setStorage(POSITION_STORAGE, absPoint)
  }
}